package com.childenglish.controller;

import com.childenglish.utils.CaptchaUtil;
import com.childenglish.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/api")
public class CaptchaController {

    @Autowired
    private CaptchaUtil captchaUtil;

    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public R<Map<String, Object>> getCaptcha(HttpSession session) {
        try {
            // 生成验证码
            CaptchaUtil.CaptchaResult captcha = captchaUtil.generateCaptcha();
            
            // 存储验证码到Session或Redis（5分钟过期）
            String sessionId = session.getId();
            String captchaKey = "captcha:" + sessionId;
            
            if (redisTemplate != null) {
                // 使用Redis存储
                redisTemplate.opsForValue().set(captchaKey, captcha.getText(), 5, TimeUnit.MINUTES);
            } else {
                // 使用Session存储
                session.setAttribute("captcha", captcha.getText());
                session.setAttribute("captcha_time", System.currentTimeMillis());
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("image", captcha.getImageBase64());
            data.put("sessionId", sessionId);
            
            return R.<Map<String, Object>>ok("验证码生成成功").data(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("生成验证码失败: " + e.getMessage());
        }
    }

    /**
     * 验证验证码
     */
    public boolean verifyCaptcha(String sessionId, String inputCaptcha) {
        if (inputCaptcha == null || inputCaptcha.trim().isEmpty()) {
            return false;
        }
        
        String captchaKey = "captcha:" + sessionId;
        String storedCaptcha = null;
        
        if (redisTemplate != null) {
            // 从Redis获取
            Object value = redisTemplate.opsForValue().get(captchaKey);
            if (value != null) {
                storedCaptcha = value.toString();
                // 验证后删除
                redisTemplate.delete(captchaKey);
            }
        } else {
            // 从Session获取（需要HttpSession，这里提供方法供其他Controller调用）
            // 实际使用时需要传入HttpSession
        }
        
        if (storedCaptcha == null) {
            return false;
        }
        
        // 不区分大小写比较
        return storedCaptcha.equalsIgnoreCase(inputCaptcha.trim());
    }

    /**
     * 从Session验证验证码（供其他Controller使用）
     */
    public boolean verifyCaptchaFromSession(HttpSession session, String inputCaptcha) {
        if (inputCaptcha == null || inputCaptcha.trim().isEmpty()) {
            return false;
        }
        
        String sessionId = session.getId();
        String captchaKey = "captcha:" + sessionId;
        String storedCaptcha = null;
        
        if (redisTemplate != null) {
            // 从Redis获取
            Object value = redisTemplate.opsForValue().get(captchaKey);
            if (value != null) {
                storedCaptcha = value.toString();
                // 验证后删除
                redisTemplate.delete(captchaKey);
            }
        } else {
            // 从Session获取
            Object captchaObj = session.getAttribute("captcha");
            if (captchaObj != null) {
                storedCaptcha = captchaObj.toString();
                // 检查是否过期（5分钟）
                Long captchaTime = (Long) session.getAttribute("captcha_time");
                if (captchaTime != null && System.currentTimeMillis() - captchaTime > 5 * 60 * 1000) {
                    session.removeAttribute("captcha");
                    session.removeAttribute("captcha_time");
                    return false;
                }
                // 验证后删除
                session.removeAttribute("captcha");
                session.removeAttribute("captcha_time");
            }
        }
        
        if (storedCaptcha == null) {
            return false;
        }
        
        // 不区分大小写比较
        return storedCaptcha.equalsIgnoreCase(inputCaptcha.trim());
    }
}

